import xml.dom.minidom

DAG_FILE="dag.xml"


class DAGParser(object):

    def __init__(self, file):
        self.DAG = {}
        self.doc = xml.dom.minidom.parse(DAG_FILE)
        self.dom = self.doc.documentElement
        self.parseDAG(self.dom)
        print(self.DAG)

    def parseDAG(self, dom):
        # Reading from <nodes> <node></node> <node></node> ... </nodes>
        for node in dom.getElementsByTagName('nodes')[0].getElementsByTagName("node"):
            self.parseNode(node)

    def parseNode(self, node):
        ID = self.getText(node.getElementsByTagName("ID")[0].childNodes)
        storage = self.getText(node.getElementsByTagName("storage")[0].childNodes)
        reuse = self.getText(node.getElementsByTagName("reuse")[0].childNodes)
        compUnits = self.getText(node.getElementsByTagName("compUnits")[0].childNodes)
        next = self.getText(node.getElementsByTagName("child")[0].childNodes)
        flag = self.getText(node.getElementsByTagName("flag")[0].childNodes)
        prev = []
        # Reading from <parents> <parent></parent> <parent></parent> </parents>
        for el in node.getElementsByTagName("parents")[0].getElementsByTagName("parent"):
            prev.append(self.getText(el.childNodes))
        self.DAG[ID] = {'storage': storage, 'reuse': reuse, 'compUnits': compUnits,
                        'next': next, 'prev': prev, 'flag': flag, 'CR' : 0.0}

    def getText(self, childNodes):
        rstring = ""
        for child in childNodes:
            if child.nodeType == child.TEXT_NODE:
                    rstring = rstring + child.data
        return rstring
        
